package org.kinglone.weixin.kit;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;

public class SecurityKit {

	/**
	 * 对str进行sha1的加密
	 * @param str
	 * @return
	 */
	public static String sha1(String str) {
		try {
			StringBuffer sb = new StringBuffer();
			MessageDigest digest = MessageDigest.getInstance("sha1");
			digest.update(str.getBytes());
			byte[] digestMsg = digest.digest();
			for(byte b:digestMsg) {
				sb.append(String.format("%02x", b));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 排序
	 * 参与签名的字段包括noncestr（随机字符串）, 有效的jsapi_ticket, timestamp（时间戳）, url
	 * 对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串string1
	 * @param params
	 * @return
	 * String string1 = "jsapi_ticket="+ jsapi_ticket +"&noncestr="+ noncestr +"&timestamp="+ String.valueOf(timestamp) +"&url="+url;
	 */
	public static String getString1(Map<String,String> params){
		StringBuilder builder = new StringBuilder();
		Map<String, String> sortMap = new TreeMap<String, String>();
		sortMap.putAll(params);		
		for(Map.Entry<String, String> s : sortMap.entrySet()){
			String k = s.getKey();
			String v = s.getValue();
			if(StringUtils.isBlank(v)){//过滤空值
				continue;
			}
			builder.append(k).append("=").append(v).append("&");
		}
		if (!sortMap.isEmpty()) {
		       builder.deleteCharAt(builder.length() - 1);//去掉最后一个参数后的"&"
		   }		
		return builder.toString();
	}
}
